<?php
declare(strict_types=1);

namespace app\controller\user;

use app\controller\BaseController;
use app\model\{User, Order, CouponOrder};
use app\service\WechatService;
use think\facade\Cache;

class TeamPromotionController extends BaseController
{
    /**
     * 团队概览
     * @return \think\response\Json
     */
    public function overview()
    {
        $user = $this->request->user;
        $merchant = $this->request->merchant;
        
        // 从缓存获取
        $cacheKey = "team_overview_{$user->id}";
        $data = Cache::get($cacheKey);
        
        if (!$data) {
            // 团队成员数
            $teamCount = User::where([
                'merchant_id' => $merchant->id,
                'parent_id' => $user->id
            ])->count();

            // 今日新增成员
            $todayCount = User::where([
                'merchant_id' => $merchant->id,
                'parent_id' => $user->id
            ])->whereDay('create_time')->count();

            // 本月新增成员
            $monthCount = User::where([
                'merchant_id' => $merchant->id,
                'parent_id' => $user->id
            ])->whereMonth('create_time')->count();

            // 团队快递订单总额
            $orderAmount = Order::where('user_id', 'in', function($query) use ($user, $merchant) {
                    $query->name('user')
                        ->where([
                            'merchant_id' => $merchant->id,
                            'parent_id' => $user->id
                        ])
                        ->field('id');
                })
                ->where('order_status', '<>', 99) // 排除已取消订单
                ->sum('fee_estimate + insure_fee');

            // 团队领券订单总额
            $couponAmount = CouponOrder::where('user_id', 'in', function($query) use ($user, $merchant) {
                    $query->name('user')
                        ->where([
                            'merchant_id' => $merchant->id,
                            'parent_id' => $user->id
                        ])
                        ->field('id');
                })
                ->where('status', 1) // 已完成的领券订单
                ->sum('order_amount');

            $data = [
                'team_count' => $teamCount,
                'today_count' => $todayCount,
                'month_count' => $monthCount,
                'order_amount' => $orderAmount,
                'coupon_amount' => $couponAmount
            ];

            // 缓存5分钟
            Cache::set($cacheKey, $data, 300);
        }

        return $this->success($data);
    }

    /**
     * 团队成员列表
     * @return \think\response\Json
     */
    public function members()
    {
        $user = $this->request->user;
        $merchant = $this->request->merchant;
        $page = $this->request->get('page', 1);
        $limit = $this->request->get('limit', 20);
        $keyword = $this->request->get('keyword', '');

        $where = [
            'merchant_id' => $merchant->id,
            'parent_id' => $user->id
        ];

        // 关键词搜索
        if ($keyword) {
            $where[] = ['mobile|nickname', 'like', "%{$keyword}%"];
        }

        $list = User::withCount([
                'orders' => function($query) {
                    $query->where('order_status', '<>', 99); // 排除已取消订单
                },
                'couponOrders' => function($query) {
                    $query->where('status', 1); // 已完成的领券订单
                }
            ])
            ->withSum([
                'orders' => function($query) {
                    $query->where('order_status', '<>', 99);
                }
            ], 'fee_estimate + insure_fee', 'order_amount')
            ->withSum([
                'couponOrders' => function($query) {
                    $query->where('status', 1);
                }
            ], 'order_amount', 'coupon_amount')
            ->where($where)
            ->field([
                'id', 'nickname', 'avatar', 'mobile',
                'create_time'
            ])
            ->order('id', 'desc')
            ->paginate([
                'list_rows' => $limit,
                'page' => $page
            ]);

        return $this->success([
            'list' => $list->items(),
            'total' => $list->total(),
            'last_page' => $list->lastPage()
        ]);
    }

    /**
     * 生成推广码
     * @return \think\response\Json
     */
    public function qrcode()
    {
        $user = $this->request->user;
        $merchant = $this->request->merchant;
        
        // 从缓存获取
        $cacheKey = "promotion_qrcode_{$user->id}";
        $qrcode = Cache::get($cacheKey);
        
        if (!$qrcode) {
            // 获取小程序配置
            $app = MerchantApplication::where([
                'merchant_id' => $merchant->id,
                'application_type' => 1 // 微信小程序
            ])->find();

            if (!$app) {
                return $this->error('商家未配置小程序');
            }

            // 生成推广参数
            $scene = "pid={$user->id}";
            $page = 'pages/index/index';

            // 调用微信接口生成小程序码
            $wechat = new WechatService($app->app_id, $app->app_secret);
            $qrcode = $wechat->createQrcode($scene, $page);
            
            if (!$qrcode) {
                return $this->error('生成推广码失败');
            }

            // 缓存24小时
            Cache::set($cacheKey, $qrcode, 86400);
        }

        return $this->success([
            'qrcode' => $qrcode
        ]);
    }
} 